/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FileEdit.java
 *
 * Created on 24-sep-2011, 12:47:38
 */
package pfc.gui;

import com.Ostermiller.Syntax.HighlightedDocument;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import pfc.arbol.FileTreeNode;
import pfc.interfaces.Salvable;

/**
 *
 * @author xandru
 */
public class FileEdit extends Editor implements Salvable {

    FileTreeNode nodo;
    ArrayList<String> lineas = new ArrayList<String>();

    /** Creates new form FileEdit */
    public FileEdit(FileTreeNode aThis) {
        nodo = aThis;
        initComponents();
        loadFile(aThis.getFile());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        bGuardar = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        texto1 = new javax.swing.JTextPane();

        bGuardar.setText("Guardar");
        bGuardar.setEnabled(false);
        bGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bGuardarActionPerformed(evt);
            }
        });

        jButton1.setText("Cerrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(bGuardar)
                .addGap(28, 28, 28)
                .addComponent(jButton1)
                .addContainerGap(264, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bGuardar)
                    .addComponent(jButton1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        texto1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                texto1KeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                texto1KeyTyped(evt);
            }
        });
        jScrollPane2.setViewportView(texto1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void bGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bGuardarActionPerformed
        // TODO add your handling code here:
        save();

        //compilar(this.nodo.getFile());
        bGuardar.setEnabled(false);

    }//GEN-LAST:event_bGuardarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
        this.getParent().remove(this);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void texto1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_texto1KeyPressed
        // TODO add your handling code here:
        bGuardar.setEnabled(true);
    }//GEN-LAST:event_texto1KeyPressed

    private void texto1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_texto1KeyTyped
        // TODO add your handling code here:
         bGuardar.setEnabled(true);
    }//GEN-LAST:event_texto1KeyTyped

    public void save() {
        System.out.println("Guardando");
        Document doc = texto1.getDocument();
        try {
            PrintWriter out = new PrintWriter(new FileOutputStream(this.nodo.getFile()));
            out.println(doc.getText(0, doc.getLength()));
            out.flush();
            out.close();

        } catch (Exception ex) {
            Logger.getLogger(FileEdit.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bGuardar;
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextPane texto1;
    // End of variables declaration//GEN-END:variables

    public JTextPane getTextPanel() {
        return texto1;
    }

    private void loadFile(File file) {
        //Document doc = texto.getDocument();
        HighlightedDocument doc1 = new HighlightedDocument();
        doc1.setHighlightStyle(HighlightedDocument.JAVA_STYLE);
        //doc1 = (HighlightedDocument) texto.getDocument();


        try {
            BufferedReader in = new BufferedReader(new FileReader(file));
            String line;
            lineas.clear();
            while ((line = in.readLine()) != null) {
                lineas.add(line);
                //doc.insertString(doc.getLength(), line + "\n", null);
                doc1.insertString(doc1.getLength(), line + "\n", null);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileEdit.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FileEdit.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BadLocationException ex) {
            Logger.getLogger(FileEdit.class.getName()).log(Level.SEVERE, null, ex);
        }
        
       
        texto1.setDocument(doc1);

    }

    private void compilar(File file) {

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        /*
         int compilationResult = compiler.run(null, null, null, file.getAbsolutePath());


        if (compilationResult == 0) {
            System.out.println("Compilation is successful");
        } else {
            System.out.println("Compilation Failed");
        }
*
         *
         */

        String[] files1 = {file.getAbsolutePath()};
        List<String> optionList = new ArrayList<String>();
        // set compiler's classpath to be same as the runtime's
        optionList.addAll(Arrays.asList("-classpath",System.getProperty("java.class.path")));


        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(files1);
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        fileManager = compiler.getStandardFileManager(diagnostics, null, null);
        compiler.getTask(null, fileManager, diagnostics, null, optionList, compilationUnits).call();
        for (Diagnostic diagnostic : diagnostics.getDiagnostics())
        {
           System.out.println("Error on line " + diagnostic.getLineNumber() + " in " + diagnostic.getMessage(Locale.ENGLISH));
        }
        try {
            fileManager.close();
        } catch (IOException ex) {
            Logger.getLogger(FileEdit.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

}
